<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'process:pipe:pmWastepipeData:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_WastePipeData"
        completeText="提交"
        :loading="loadingRef"
        :auth="'process:pipe:pmWastepipeData:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProcessPipePmWastepipeDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmWastepipeData,
    pmWastepipeDataSave,
    pmWastepipeDataForm,
  } from '/@/api/process/pipe/pmWastepipeData';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('process.pipe.pmWastepipeData');
  const { showMessage } = useMessage();
  const record = ref<PmWastepipeData>({} as PmWastepipeData);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    //value: record.value.isNewRecord ? t('新增管道废除') : t('编辑管道废除'),
    value: t('发起管道废除申请'),
  }));

  const loadingRef = ref(false);
  const moreInfo = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('地址'),
      field: 'caddr',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      required: true,
    },
    {
      label: t('废管说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('废管利旧'),
      field: 'breuse',
      component: 'Checkbox',
      componentProps: ({ formModel }) => {
        return {
          options: [{ label: '', value: 1 }],
          onChange: (v) => {
            if (v.target.checked) {
              moreInfo.value = true;
            } else {
              moreInfo.value = false;
            }
            formModel['breuse'] = v.target.checked ? 1 : 0;
          },
        };
      },
      //required: true,
      colProps: { lg: 8, md: 24 },
    },
    {
      label: t('废弃通知附件'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmWastePipeData_notify_file',
        uploadType: 'all',
      },
      // 文件上传的必填验证实例
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmWastePipeData_notify_file__len'] || 0;
              if (len == 0) reject(t('请上传废弃通知附件'));
              else resolve();
            });
          },
        },
      ],
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('废管利旧补充信息'),
      field: 'moreInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: computed(() => moreInfo.value || record.value.breuse == '1'),
    },
    {
      label: t('管道去向'),
      field: 'dealType',
      component: 'RadioGroup',
      componentProps: {
        dictType: 'zf_pipe_deal_type',
        allowClear: true,
      },
      ifShow: computed(() => moreInfo.value || record.value.breuse == '1'),
    },
    {
      label: t('管道规格'),
      field: 'pipeDesc',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      ifShow: computed(() => moreInfo.value || record.value.breuse == '1'),
    },
    {
      label: t('管道利旧备注'),
      field: 'dealRemarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      ifShow: computed(() => moreInfo.value || record.value.breuse == '1'),
    },
    {
      label: t('利旧记录表'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmWastePipeData_reuse_file',
        uploadType: 'all',
      },
      // 文件上传的必填验证实例
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmWastePipeData_reuse_file__len'] || 0;
              if (len == 0) reject(t('请上传利旧记录表'));
              else resolve();
            });
          },
        },
      ],
      colProps: { lg: 24, md: 24 },
      ifShow: computed(() => moreInfo.value || record.value.breuse == '1'),
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    moreInfo.value = false;
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmWastepipeDataForm(data);
    record.value = (res.pmWastepipeData || {}) as PmWastepipeData;
    record.value.__t = new Date().getTime();
    if (record.value.breuse === '0') {
      record.value.breuse = '';
    }
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      console.log(data);
      if (!data.breuse) {
        data.breuse = '0';
      }
      // console.log('submit', params, data, record);
      const res = await pmWastepipeDataSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
